import defaultAxios from 'axios';
import Progress from 'nprogress';
import 'nprogress/nprogress.css';
import { message } from 'antd';

const axios = defaultAxios.create({
  baseURL: 'http://fangadmin.shbwyz.com/',
});

axios.interceptors.request.use((config) => {
  config.headers.Authorization = sessionStorage.getItem('token') || '';
  return config;
});

axios.interceptors.response.use((data) => {
  return data;
});

const whiteList = [
  {
    method: 'get',
    url: '/getvisitorlist',
  },
  {
    method: 'get',
    url: '/getservicelist',
  },
];

defaultAxios.interceptors.request.use(
  (config) => {
    Progress.start();
    config.headers.Authorization = sessionStorage.getItem('token') || '';
    return config;
  },
  (err) => {
    return err;
  },
);

defaultAxios.interceptors.response.use(
  (data: any) => {
    console.log(data);
    const flag = whiteList.some(
      (item) =>
        item.method === data.config.method &&
        item.url.includes(data.config.url),
    );
    if (flag) {
      message.success('请求成功');
    }
    Progress.done();
    return data;
  },
  (err) => {
    if (err.response.status === 500) {
      message.error('服务端错误');
    } else if (err.response.status === 404) {
      message.error('页面不存在');
    }
    return err;
  },
);

export { axios, defaultAxios };
